// 导入封装的组件
import Loading from './src/components/loadingBar/loading'

const components = {

  // 通过install来安装组件
  install(Vue, options) {

    // 创建"子类"方便挂载
    const Loadings = Vue.extend(Loading);
    let loaded;

    function $loadingBar() {
      return new Promise(resolve => {
        // 第一次调用
        if (!loaded) {

          loaded = new Loadings();
          // 手动创建一个未挂载的实例
          loaded.$mount();

          if (options) {
            if (options.color){
              loaded.$set(loaded, 'innerColor', options.color);
            }
            if (options.height){
              loaded.$set(loaded, 'innerHeight',options.height);
            }
          }

          // 挂载
          document.querySelector('body').appendChild(loaded.$el);
        }
        resolve();
      });
    }

    $loadingBar.start = () => {
      return new Promise(resolve => {
        if (!loaded) {
          $loadingBar();
        }
        loaded.start();
        resolve();
      });
    };

    $loadingBar.finish = () => {
      return new Promise(resolve => {
        if (!loaded) {
          $loadingBar();
        }
        loaded.finish(false);
        resolve();
      });
    };

    $loadingBar.failed = () => {
      return new Promise(resolve => {
        if (!loaded) {
          $loadingBar();
        }
        loaded.failed();
        resolve();
      });
    };

    $loadingBar.update = (percent) => {
      return new Promise(resolve => {
        if (!loaded) {
          $loadingBar();
        }
        loaded.update(percent);
        resolve();
      });
    };

    Vue.prototype.$loadingBar = $loadingBar;
  }
};




// auto install
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(components)
}

export default components
